package com.agileai.portal.controller.address;

import java.util.List;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.controller.core.SimpleHandler;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.address.ContactGroupTreeQuery;

public class ContactGroupTreeProviderHandler extends SimpleHandler
{
	  public ContactGroupTreeProviderHandler()
	  {
	    this.serviceId = buildServiceId(ContactGroupTreeQuery.class);
	  }

	  public ViewRenderer prepareDisplay(DataParam param) {
		  ContactGroupTreeQuery treeManage = getService();
		  String datas = null;
		  List<DataRow> records = treeManage.findTreeRecords(param);
		  datas = this.buildTreeListJson(records);
		  this.setAttribute("datas",datas);
		  return new LocalRenderer(getPage());
	  }
	  
	  private String buildTreeListJson(List<DataRow> records){
			String result = null;
			try {
				JSONArray jsonArray = new JSONArray();
				for (int i=0;i < records.size();i++){
					DataRow row = records.get(i);
					String itemCode = String.valueOf(row.get("GRP_ID"));
					String itemName = String.valueOf(row.get("GRP_NAME"));
					String itemPCode = String.valueOf(row.get("GRP_PID"));
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("id", itemCode);
					jsonObject.put("name", itemName);
					jsonObject.put("parentId", itemPCode);
					jsonArray.put(jsonObject);
				}
				result = jsonArray.toString();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result;
		}

	  protected ContactGroupTreeQuery getService() {
	    return (ContactGroupTreeQuery)lookupService(getServiceId());
	  }
	}